import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Q1 {

    private static final String CHARSET = "utf-8";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Socket Server
     */
    public void socketServer() {
        // Initialize socket server service
        try (ServerSocket server = new ServerSocket(5000)) {
            // Client request listener
            while (true) {
                // Listens for a connection to be made to this socket and accepts it
                Socket client = server.accept();
                // Create a thread handle request
                new Thread(() -> {
                    String line;
                    String date = sdf.format(new Date());
                    StringBuilder sb = new StringBuilder();
                    String link = client.getInetAddress().getHostAddress() + ":" + client.getPort();

                    System.out.println(date + " - " + link);
                    try (BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET));
                         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), CHARSET))) {

                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }

                        System.out.println("Request content: ");
                        System.out.println(sb.toString());
                        bw.write("Server was accepted this request.");

                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Socket Client
     */
    public void socketClient() {
        String line;
        String date = sdf.format(new Date());
        StringBuilder sb = new StringBuilder();

        try (Socket socket = new Socket("127.0.0.1", 5000)) {
            new Thread(() -> {

            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
